package omg.loot;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.HashMap;

import javax.media.opengl.GL2;
import javax.media.opengl.GLException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;

public class TextureManager {
   /** The buffer holding the indices */
   public static ByteBuffer indexBuffer;
   public static float tAtlasWidth;
   public static float tAtlasHeight;
   protected GL2 gl;

   public TextureManager(final GL2 gl) {
      this.gl = gl;

      final byte[] indices = {0, 1, 2, 0, 2, 3};
      //Luodaan indices-bufferi:
      indexBuffer = ByteBuffer.allocateDirect(indices.length);
      indexBuffer.put(indices);
      indexBuffer.position(0);
   }

   public void kill() {
      gl = null;
   }

   public void setSprite(final Sprite sprite) {
      gl.glTexCoordPointer(2, GL2.GL_FLOAT, 0, sprite.texCoords);
      gl.glVertexPointer(2, GL2.GL_FLOAT, 0, sprite.vertices);
   }

   public void draw(final GL2 gl) {
      gl.glDrawElements(GL2.GL_TRIANGLES, 6, GL2.GL_UNSIGNED_BYTE, indexBuffer);
   }

   public Texture loadTextureAtlas(final String filename) {
      Texture texture = null;
      try {
         texture = TextureIO.newTexture(new File(this.getClass().getResource(filename).toURI()), true);
         tAtlasWidth = texture.getWidth();
         tAtlasHeight = texture.getHeight();
      } catch (final GLException e) {
         e.printStackTrace();
      } catch (final IOException e) {
         e.printStackTrace();
      } catch (final URISyntaxException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      //Clean up
      System.gc();
      return texture; //Palautetaan viite tekstuuriin
   }

   public HashMap<String, Sprite> parseXML(final String filename) {
      TextureHandler textureHandler;
      //Käsittele xml ja tallenna olennainen:
      try {
         /** Handling XML */
         final SAXParserFactory spf = SAXParserFactory.newInstance();
         final SAXParser sp = spf.newSAXParser();
         final XMLReader xr = sp.getXMLReader();

         /** Create handler to handle XML Tags ( extends DefaultHandler ) */
         textureHandler = new TextureHandler();
         xr.setContentHandler(textureHandler);
         xr.parse(new InputSource(this.getClass().getResourceAsStream(filename)));         
      } catch (final Exception e) {
         e.printStackTrace();
         return null;
      }
      return textureHandler.textureMap;
   }
}

class TextureHandler extends DefaultHandler {
   protected HashMap<String, Sprite> textureMap = new HashMap<String, Sprite>();

   /** Called when tag starts ( ex:- <name>AndroidPeople</name>
    * -- <name> )*/
   @Override
   public void startElement(final String uri, final String localName, final String qName,
         final Attributes atts) throws SAXException {
      if (qName.equalsIgnoreCase("SubTexture")) {        
         final int x,y;
         final float leveys,korkeus;
         final String name = atts.getValue("name");
         korkeus = Float.parseFloat(atts.getValue("height"));
         leveys = Float.parseFloat(atts.getValue("width"));
         x = Integer.parseInt(atts.getValue("x"));
         y = Integer.parseInt(atts.getValue("y"));         
         final Sprite sprite = new Sprite(x, y, leveys, korkeus);
         textureMap.put(name, sprite);
      }
   }

   /** Called when tag closing ( ex:- <name>AndroidPeople</name>
    * -- </name> )*/
   @Override
   public void endElement(final String uri, final String localName, final String qName)
   throws SAXException {}

   /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
    * -- to get AndroidPeople Character ) */
   @Override
   public void characters(final char[] ch, final int start, final int length)
   throws SAXException {}
}